package com.ws.shop.app;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class AuctionApp {

	private static Logger log = Logger.getLogger(AuctionApp.class);
	private static String SRCDIR = Config.getInstance().getInputdir();
	private static int sleeptime = Config.getInstance().getSleeptime();
	private static Connection connect = null;

	private boolean runflag = true;

	public void run() {
		try {
			log.info("AppRule开始......");
			while (runflag) {
				try {
					if (connect != null && !connect.isClosed() && connect.isValid(0)) {
						this.scanSrcDir();
					} else {
						renewConnect();
					}
					Thread.sleep(sleeptime);
				} catch (Exception e) {
					e.printStackTrace();
					renewConnect();
					log.error("......处理文件错误......");
				}
			}
		} finally {
		}
	}

	// 扫描文件......
	private void scanSrcDir() {
		File srcDir = new File(SRCDIR);
		File subFiles[] = srcDir.listFiles(new RuleFilter());
		int size = subFiles.length;
		log.info(size + "个文件待处理......");
		BufferedReader reader = null;
		for (int i = 0; i < size; i++) {
			log.info("处理文件:" +  subFiles[i].getName());
			try {
				reader = new BufferedReader(new FileReader(subFiles[i]));
				String text = null;
				while ((text = reader.readLine()) != null) {
					new AuctionHandler(connect,text).handler();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (reader != null) {
						reader.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void renewConnect() {
		if (connect != null) {
			ConnectManager.close(connect, null, null);
			log.info("++++++++++数据库重新连接+++++++++++");
			try {
				connect = ConnectManager.getConnection();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
		}
	}

	// 程序开始
	public static void main(String[] agrs) {
		log.info("++++++++++++++++++程序开始+++++++++++++++++++++");
		Config config = Config.getInstance();
		PropertyConfigurator.configure(config.getLogconfig());
		try {
			connect = ConnectManager.getConnection();
			log.info("+++++++++++++++数据库练成++++++++++++++");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			System.exit(-1);
		}
	}

}

/**
 * 
 * 规则过滤器，备用
 * 
 * @author Administrator
 * 
 */
class RuleFilter implements FileFilter {
	public boolean accept(File pathname) {
		return true;
	}
}
